package com.xneure.database.metaobject;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.xneure.database.annotation.DBField;
import com.xneure.database.annotation.OutreachAction;
import com.xneure.database.sql.handler.HandlerType;
import com.xneure.database.sql.handler.SqlHandler;
import com.xneure.utils.bean.ClassProperty;

public class FieldMetaObject extends MetaObject{
	private String name;
	private ClassProperty field;
	private int[] ignore = {Modifier.TRANSIENT,Modifier.FINAL,Modifier.STATIC};
	private TableMetaObject parent;

	public FieldMetaObject(TableMetaObject tableMetaObject,ClassProperty field){
		super(field.getField().getType());
		this.parent = tableMetaObject;
		this.field = field;
		setAnnotation(field.getField().getAnnotation(DBField.class));
		name = getFieldName(field.getField());
	}

	public boolean isIdKey(){
		if(null != getAnnotation()){
			DBField dfDbField = (DBField)getAnnotation();
			return dfDbField.primaryKey();
		}else{
			return "id".equals(name);
		}
	}

	public Field getField(){
		return field.getField();
	}

	public String getName(){
		return name;
	}

	protected String getFieldName(Field field){
		if(null != getAnnotation()){
			if(isIgnore() == false && getAnnotation().value().isEmpty() == false){
				return getAnnotation().value();
			}
		}
		return field.getName();
	}

	@Override
	public DBField getAnnotation(){
		return (DBField)super.getAnnotation();
	}

	public boolean isIgnore(){
		if(null != getAnnotation() && (getAnnotation().ignore() || getAnnotation().relation().length() > 0)){
			return true;
		}
		int modifiers = field.getField().getModifiers();
		for(int val:ignore){
			if((modifiers & val) != 0){
				return true;
			}
		}
		return false;
	}

	public Object getValue(Object obj){
		Object fieldValue = field.getValue(obj);
		return SqlHandler.getValueConvert().sqlValue(this,fieldValue);
	}

	public OutreachAction getOutreachAction(){
		return field.getField().getAnnotation(OutreachAction.class);
	}

	public boolean checkOutreachAction(HandlerType ht){
		OutreachAction oa = getOutreachAction();
		if(oa == null){
			oa = parent.getType().getAnnotation(OutreachAction.class);
		}
		if(null != oa){
			HandlerType[] value = oa.value();
			if(value != null){
				for(HandlerType _ht:value){
					if(_ht == ht){
						return true;
					}
				}
			}
		}
		return false;
	}
}
